<?php
function DoSiteRepay($deal,$repaylist,$deal_repay_id, $platformNo,$post_url,$mchnt_user_id){
	
		require_once APP_ROOT_PATH."app/Lib/deal.php";
		require_once APP_ROOT_PATH."app/Lib/common.php";
	
		$adm_session = es_session::get(md5(APP_CONF("AUTH_KEY")));
		$adm_name = $adm_session['adm_name'];
		$adm_id = intval($adm_session['adm_id']);
		
		if($adm_id == 0)
		{
			//已登录
			return json_encode(array("status"=>0 ,"deal_id"=>$deal['id'], "info" =>'请先登陆'));
		}
		
		$sql = "select l_key from ".DB_PREFIX."deal_repay where has_repay in(0,2) and id =".$deal_repay_id;					
		$l_key = intval($GLOBALS['db']->getOne($sql));
	
		set_time_limit(0);
		require_once APP_ROOT_PATH."system/libs/user.php";
		$fee = 0;
		$k=0;
		foreach($repaylist as $k=>$v){
			$detail = array();
				
			//平台收取：借款者 的管理费 + 管理逾期罚息
			$detail['manage_fee'] = $v['repay_manage_money'] + $v['repay_manage_impose_money'] + $v['mortgage_fee'];
				
			//==============================投资者获取的，费用===================================
			
			$detail['deal_repay_id'] = $deal_repay_id;
			$detail['deal_id'] = $deal['id'];
			$detail['deal_load_id'] = $v['load_id'];
			$detail['deal_load_repay_id'] = $v['id'];
			
			$temp_detail = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."fuioupay_cp_transaction_detail WHERE deal_repay_id=".$deal_repay_id." AND deal_id=".$detail['deal_id']." AND deal_load_id=".$detail['deal_load_id']." AND deal_load_repay_id=".$detail['deal_load_repay_id']);
			$mode = "";
			$where = "";
			if($temp_detail){
				$detail = $temp_detail;
				$mode = "UPDATE";
				$where = "id=".$temp_detail['id'];
			}
			else{
				$detail['is_callback'] = 0;
				$mode = "INSERT";
			}
			$detail['repay_manage_impose_money'] = $v['repay_manage_impose_money'];//平台收取 借款者 的管理费逾期罚息
			$detail['impose_money'] = $v['impose_money'];//投资者收取 借款者 的逾期罚息			
			$detail['repay_status'] = intval($v['status']) - 1;//还款状态
			$detail['true_repay_time'] = TIME_UTC;//还款时间
			
			require_once APP_ROOT_PATH.'system/collocation/fuioupay/transferBu.php';
			
			//投资人会员编号
			if ($v['t_user_id']){
				//债权转让后,还款时，转给：承接者, 在债权转让后需要更新 fanwe_deal_load_repay.t_user_id 数据值
				$detail['user_id'] = $v['t_user_id'];
			}else{
				$detail['user_id'] = $v['user_id'];
			}
		
			//投资者获取的，费用 [宝付会自动扣除 $detail['fee'] 部分，所以最终获得的收入为：$v['month_repay_money'] + $v['impose_money'] - $v['manage_money'] - $v['manage_interest_money']
			$detail['amount'] = round($v['month_repay_money'] + $v['impose_money'],2);
		
			//平台收取：投资者 的投资金额管理费 + 利息管理费
			$detail['fee'] = round($v['manage_money']+$v['manage_interest_money'],2);
				
			$GLOBALS['db']->autoExecute(DB_PREFIX."fuioupay_cp_transaction_detail",$detail,$mode,$where);
			
			if($mode=="INSERT"){
				$detail_id = $GLOBALS['db']->insert_id();
			}else{
				$detail_id = $temp_detail['id'];
			}
			
			//转账
			if($detail['is_callback'] == 0){
				//$rs = transferBu($detail['user_id'],$deal['user_id'],$detail['amount'],$platformNo,$post_url,$deal['id']);
				$rs = transferBu($detail['user_id'],$mchnt_user_id,$detail['amount'],$platformNo,$post_url,$deal['id']);
				if($rs['resp_code']=="0000"){
					$detail['is_callback'] = 1;
					$GLOBALS['db']->query("UPDATE ".DB_PREFIX."fuioupay_cp_transaction_detail SET is_callback=1 WHERE id=".$detail_id);
				}
			}
			//管理费 - 投资者
			if($detail['is_callback'] == 1){
				if($detail['fee'] != 0)
				{
					$rs = transferBu($mchnt_user_id,$detail['user_id'],$detail['fee'],$platformNo,$post_url,$deal['id']);
				}
				if($rs['resp_code']=="0000" || $detail['fee'] ==0){
					$detail['is_callback'] = 2;
					$GLOBALS['db']->query("UPDATE ".DB_PREFIX."fuioupay_cp_transaction_detail SET is_callback=2 WHERE id=".$detail_id);
				}
			}
			//管理费 - 借款人
			if($detail['is_callback'] == 2){
				//if($detail['manage_fee'] != 0)
					//$rs = transferBu($mchnt_user_id,$deal['user_id'],$detail['manage_fee'],$platformNo,$post_url,$deal['id']);
					//$rs = transferBu($mchnt_user_id,$deal['user_id'],$detail['manage_fee'],$platformNo,$post_url,$deal['id']);
				//if($detail['manage_fee'] ==0){
					$detail['is_callback'] = 3;
					$GLOBALS['db']->query("UPDATE ".DB_PREFIX."fuioupay_cp_transaction_detail SET is_callback=3 WHERE id=".$detail_id);
				//}
			}
		}

		
		$sql = "select * from ".DB_PREFIX."fuioupay_cp_transaction_detail where is_callback= 3 AND deal_repay_id=".$deal_repay_id." and deal_id = ".$deal['id'];
		$list = $GLOBALS['db']->getAll($sql);

		foreach($list as $k=>$v){
			$load_repay = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal_load_repay where repay_id= ".$deal_repay_id." AND  id = ".$v['deal_load_repay_id']);
				
			//repay_status,repay_manage_impose_money							
	
			$detail = array();
			$detail['true_repay_time'] = $v["true_repay_time"];//还款时间
			$detail['true_repay_date'] = to_date($v["true_repay_time"]);
			$detail['is_site_repay'] = 1;
			$detail['status'] = 0;
			
			$detail['true_repay_money'] =$load_repay["repay_money"];
			$detail['true_self_money'] = $load_repay['self_money'];
			$detail['true_interest_money'] =  $load_repay['interest_money'];
			$detail['true_manage_money'] = $load_repay['manage_money'];
			$detail['true_manage_interest_money'] = $load_repay["manage_interest_money"];
			$detail['true_repay_manage_money'] = $load_repay["repay_manage_money"];
			$detail['true_interestrate_money']= (float)$load_repay['interestrate_money'];
			$detail['impose_money'] = $v["impose_money"];//投资者收取 借款者 的逾期罚息
			$detail['repay_manage_impose_money'] = $v["repay_manage_impose_money"];//平台收取 借款者 的管理费逾期罚息
			
			$detail['true_reward_money'] = (float)$load_repay['reward_money'];
            $detail['true_mortgage_fee'] = $load_repay['mortgage_fee'];

			$detail['status'] = $v["repay_status"];//还款状态
			$detail['has_repay'] = 1;//0未收到还款，1已收到还款
	
			$GLOBALS['db']->autoExecute(DB_PREFIX."deal_load_repay",$detail,'UPDATE'," has_repay = 0 and id = ".intval($v['deal_load_repay_id']));
			
			if($GLOBALS['db']->affected_rows() > 0){
				//会员分销返利
				get_referrals($v['deal_load_repay_id']);

				if($deal['extra_money_rate'] > 0){
					$extra_money = $detail['true_self_money']*$deal['extra_money_rate']*0.01;
					if($extra_money > 0 )
						modify_account(array("money"=>$extra_money),$load_repay['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($load_repay["l_key"]+1)."期,额外奖励",56);
				}

//				get_distribution_referrals($v['deal_load_repay_id']);

				//短信通知回款
				if($load_repay['t_user_id'] > 0) {
					$loan_user_info = get_user("*", intval($load_repay['t_user_id']));
					$loan_user_info['old_id'] = intval($load_repay['user_id']);
				}else{
					$loan_user_info  = get_user("*",intval($load_repay['user_id']));
				}

				
				
				$deal = get_deal(intval($load_repay['deal_id']));
				
				$kk = $load_repay['l_key'];
				
				//更新用户账户资金记录
				/*modify_account(array("money"=>$detail['true_repay_money']),$loan_user_info['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,收到本金：".$detail['true_self_money']."，利息：".$detail['true_interest_money']."，总额：".$detail['true_repay_money'],5,1);
				
				if($detail['true_manage_money'] > 0)
					modify_account(array("money"=>-$detail['true_manage_money']),$loan_user_info['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,投标管理费",20,1);
	            
				//利息管理费
				if($detail['true_manage_interest_money']!=0)
					modify_account(array("money"=>-$detail['true_manage_interest_money']),$loan_user_info['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,投标利息管理费",20,1);
					
				if($user_load_data['impose_money'] != 0)
					modify_account(array("money"=>$detail['impose_money']),$loan_user_info['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,逾期罚息",21,1);
				*/
				//投资者奖励 - 加息券
				if($detail['true_interestrate_money']!=0){
					
					//$in_data = array();
					//$in_data['user_id'] = $loan_user_info['id'];
					//$rs = transferBu($loan_user_info['id'],$mchnt_user_id,$detail['true_interestrate_money'],$platformNo,$post_url,$deal['id'],0,53,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,加息券收益"); 
					/*if($rs['resp_code']=="0000"){
						
						//$in_data['status'] = 1;
						//$in_data['pay_time'] = to_date(TIME_UTC);
						*/
						//modify_account(array("money"=>$detail['true_interestrate_money']),$loan_user_info['old_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,加息券收益",53);
					
					/*}
					else{
						//$in_data['status'] = 0;
					}*/
					
					//$in_data['info'] = "[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,加息券收益";
					//$in_data['money'] = $detail['true_interestrate_money'];
					
					//$GLOBALS['db']->autoExecute(DB_PREFIX."deal_interestrate_money",$in_data);
				}
				
				//投资者奖励
				if($detail['true_reward_money']!=0){
					$rs = transferBu($loan_user_info['id'],$mchnt_user_id,$detail['true_reward_money'],$platformNo,$post_url,$deal['id'],0,28,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,奖励收益");
					/*if($rs['resp_code']=="0000")
						modify_account(array("money"=>$detail['true_reward_money']),$loan_user_info['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,奖励收益",28,1);*/
				}
				
				
				
				$load_repay_rs = $GLOBALS['db']->getRow("SELECT (sum(true_interest_money) + sum(impose_money)) as shouyi,sum(impose_money) as total_impose_money FROM ".DB_PREFIX."deal_load_repay WHERE id=".$load_repay['id']);
				$all_shouyi_money= number_format($load_repay_rs['shouyi'],2);
				$all_impose_money = number_format($load_repay_rs['total_impose_money'],2);
				
				$unext_loan = $GLOBALS['db']->getRow("select *,repay_time as repay_day,repay_money as month_repay_money from ".DB_PREFIX."deal_load_repay where deal_id = ".$load_repay['deal_id']." AND l_key > ".$load_repay['l_key']);
				
				send_repay_reback_sms_mail($deal,$loan_user_info,$unext_loan,$detail,$all_shouyi_money,$all_impose_money);
			}
				
		}
	
		//更新用户回款计划
		syn_deal_repay_status($deal['id'],$deal_repay_id);
		
		//借款人
		$deal_repay = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal_repay where id=".$deal_repay_id);
		
		if($deal_repay['has_repay'] == 1)
		{
			////更新用户账户资金记录
			/*modify_account(array("money"=>-$deal_repay["true_repay_money"]),$deal_repay['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($deal_repay['l_key']+1)."期,偿还本息",4,1);*/
			
			//借款者返佣
			$rebate_rs = get_rebate_fee($deal_repay['user_id'],"borrow");
			$true_manage_money_rebate = $deal_repay['manage_money']* floatval($rebate_rs['rebate'])/100;
			if($true_manage_money_rebate!=0){
				/*ok*/
				$reback_memo = sprintf($GLOBALS['lang']["BORROW_REBATE_LOG"],$deal["url"],$deal["name"],$deal["user"]["user_name"],intval($kk)+1);
				reback_rebate_money($deal_repay['user_id'],$true_manage_money_rebate,"borrow",$reback_memo);
			}
			/*
			if($deal_repay['impose_money']!=0)
			{
				modify_account(array("money"=>-$deal_repay['impose_money']),$deal_repay['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($deal_repay['l_key']+1)."期,逾期罚息",11,1);
			}
			
			if($deal_repay['true_manage_money'] > 0 ) //&& $get_manage == 0
			{
				modify_account(array("money"=>-$deal_repay['true_manage_money']),$deal_repay['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($deal_repay['l_key']+1)."期,借款管理费",10,1);
			}
			
			if($deal_repay['true_mortgage_fee'] > 0)
				modify_account(array("money"=>-$deal_repay['true_mortgage_fee']),$deal_repay['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($deal_repay['l_key']+1)."期,抵押物管理费",27,1);
			
			if($deal_repay['manage_impose_money']!=0 )
				modify_account(array("money"=>-$deal_repay['manage_impose_money']),$deal_repay['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($deal_repay['l_key']+1)."期,逾期管理费",12,1);
				*/
			/*****************************/
			$s_count =  $GLOBALS['db']->getOne("SELECT count(*) FROM  ".DB_PREFIX."deal_load_repay where deal_id=".$deal["id"]." AND l_key=".$l_key." and has_repay = 0");
			
			if($s_count == 0){
				
				$rs_sum = $GLOBALS['db']->getRow("SELECT sum(true_repay_money) as total_repay_money,sum(true_self_money) as total_self_money,sum(true_interest_money) as total_interest_money,sum(true_repay_manage_money) as total_manage_money,sum(impose_money) as total_impose_money,sum(repay_manage_impose_money) as total_repay_manage_impose_money,sum(true_mortgage_fee) as total_mortgage_fee FROM  ".DB_PREFIX."deal_load_repay where deal_id=".$deal["id"]." AND l_key=".$l_key."  and has_repay = 1");
				
				$deal_load_list = get_deal_load_list($deal);
				
				//统计网站代还款
				$rs_site_sum = $GLOBALS['db']->getRow("SELECT sum(true_repay_money) as total_repay_money,sum(true_self_money) as total_self_money,sum(true_repay_manage_money) as total_manage_money,sum(impose_money) as total_impose_money,sum(repay_manage_impose_money) as total_repay_manage_impose_money,sum(true_mortgage_fee) as total_mortgage_fee FROM  ".DB_PREFIX."deal_load_repay where deal_id=".$deal["id"]." AND l_key=".$l_key." and is_site_repay=1 and has_repay = 1");
				
				$repay_data['status'] = (int)$GLOBALS['db']->getOne("SELECT `status` FROM  ".DB_PREFIX."deal_load_repay where deal_id=".$id." AND l_key=".$l_key." and has_repay = 1 AND is_site_repay=1  ORDER BY l_key DESC");
				$repay_data['true_repay_time'] = TIME_UTC;
				$repay_data['true_repay_date'] = to_date(TIME_UTC);
				$repay_data['has_repay'] = 1;
				$repay_data['impose_money'] = floatval($rs_sum['total_impose_money']);
				$repay_data['true_self_money'] = floatval($rs_sum['total_self_money']);
				$repay_data['true_repay_money'] = floatval($rs_sum['total_repay_money']);
				if($get_manage==0)
					$repay_data['true_manage_money'] = floatval($rs_sum['total_manage_money']);
				$repay_data['true_mortgage_fee'] =  floatval($rs_sum['total_mortgage_fee']);
				$repay_data['true_interest_money'] = floatval($rs_sum['total_interest_money']);
				$repay_data['manage_impose_money'] = floatval($rs_sum['total_repay_manage_impose_money']);
				$rebate_rs = get_rebate_fee($deal['user_id'],"borrow");
				$repay_data['true_manage_money_rebate'] = $repay_data['true_manage_money']* floatval($rebate_rs['rebate'])/100;
				
				//借款者返佣
				if($repay_data['true_manage_money_rebate']!=0){
					/*ok*/
					$reback_memo = sprintf(L("BORROW_REBATE_LOG"),$deal["url"],$deal["name"],$deal["user"]["user_name"],intval($l_key)+1);
					reback_rebate_money($deal['user_id'],$repay_data['true_manage_money_rebate'],"borrow",$reback_memo);
				}
				
				
				$GLOBALS['db']->autoExecute(DB_PREFIX."deal_repay",$repay_data,"UPDATE"," deal_id=".$deal['id']." AND l_key=".$l_key." and has_repay in (0,2) ");
				
				$impose_day = ceil((to_timespan(to_date(TIME_UTC,"Y-m-d"),"Y-m-d") -  $deal_load_list[$l_key]['repay_day'])/24/3600);
				if($impose_day > 0){
					//VIP 逾期还款降级
					$type = 2;
					$type_info = 5;
					$resultdate = syn_user_vip($deal['user_id'],$type,$type_info);
					
					if($impose_day < app_conf('YZ_IMPSE_DAY')){
						modify_account(array("point"=>trim(app_conf('IMPOSE_POINT'))),$deal['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($vv["l_key"]+1)."期,逾期还款",11);
						
					}
					else{
						modify_account(array("point"=>trim(app_conf('YZ_IMPOSE_POINT'))),$deal['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($vv["l_key"]+1)."期,严重逾期",11);
					}
				}
				else{
					//VIP 代还款降级 
					$type = 2;
					$type_info = 6;
					$resultdate = syn_user_vip($deal['user_id'],$type,$type_info);
				}
				
				if($rs_site_sum){
					$r_msg = "网站代还款";
					if($rs_site_sum['total_repay_money'] > 0){
						$r_msg .=",本息：".format_price($rs_site_sum['total_repay_money']);
					}
					if($rs_site_sum['total_impose_money'] > 0){
						$r_msg .=",逾期费用：".format_price($rs_site_sum['total_impose_money']);
					}
					if($rs_site_sum['total_manage_money'] > 0 && $get_manage ==0){
						$r_msg .=",管理费：".format_price($rs_site_sum['total_manage_money']);
					}
                    if($rs_site_sum['true_mortgage_fee'] > 0 ){
                        $r_msg .=",抵押物管理费：".format_price($rs_site_sum['total_mortgage_fee']);
                    }
					if($rs_site_sum['total_repay_manage_impose_money'] > 0){
						$r_msg .=",逾期管理费：".format_price($rs_site_sum['total_repay_manage_impose_money']);
					}
					repay_log($deal_load_list[$l_key]['repay_id'],$r_msg,$deal['user_id'],$adm_session['adm_id']);
				}
				
				if($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."generation_repay WHERE deal_id=".$deal['id']." AND repay_id=".$deal_load_list[$l_key]['repay_id']."")==0){
					$generation_repay['deal_id'] = $deal['id'];
					$generation_repay['repay_id'] = $deal_load_list[$l_key]['repay_id'];
					
					$generation_repay['admin_id'] = $adm_session['adm_id'];
					$generation_repay['agency_id'] = $deal['agency_id'];
					$generation_repay['repay_money'] = $rs_site_sum['total_repay_money'];
					$generation_repay['self_money'] = $rs_site_sum['total_self_money'];
					$generation_repay['impose_money'] = $rs_site_sum['total_impose_money'];
					if($get_manage==0)
						$generation_repay['manage_money'] = $rs_site_sum['total_manage_money'];
                    $generation_repay['mortgage_fee'] = $rs_site_sum['total_mortgage_fee'];
					$generation_repay['manage_impose_money'] = $rs_site_sum['total_repay_manage_impose_money'];
					$generation_repay['create_time'] = TIME_UTC;
					$generation_repay['create_date'] = to_date(TIME_UTC,"Y-m-d");
					
					$GLOBALS['db']->autoExecute(DB_PREFIX."generation_repay",$generation_repay);
					
					$site_money_data['user_id'] = $deal['user_id'];
					$site_money_data['create_time'] = TIME_UTC;
					$site_money_data['create_time_ymd'] = to_date(TIME_UTC,"Y-m-d");
					$site_money_data['create_time_ym'] = to_date(TIME_UTC,"Ym");
					$site_money_data['create_time_y'] = to_date(TIME_UTC,"Y");
					if($rs_sum['total_manage_money']!=0 && $get_manage==0){
						$site_money_data['memo'] = "[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($l_key)."期,借款管理费";
						$site_money_data['type'] = 10;
						$site_money_data['money'] = $rs_sum['total_manage_money'];
						$GLOBALS['db']->autoExecute(DB_PREFIX."site_money_log",$site_money_data,"INSERT");
					}
					if($rs_sum['total_repay_manage_impose_money']!=0){
						$site_money_data['memo'] = "[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($l_key)."期,逾期管理费";
						$site_money_data['type'] = 12;
						$site_money_data['money'] = $rs_sum['total_repay_manage_impose_money'];
						$GLOBALS['db']->autoExecute(DB_PREFIX."site_money_log",$site_money_data,"INSERT");
					}
					
				}
				
			}
			
			syn_deal_status($deal['id']);
			syn_transfer_status(0,$deal['id']);
			/*****************************/		
		
			return array("status"=>1 ,"deal_id"=>$deal['id'], "info" =>'代还款执行完毕',"jump"=>"m.php?m=Deal&a=index&");
		}
		else
		{
			return array("status"=>1 ,"deal_id"=>$deal['id'], "info" =>'代还款执行失败',"jump"=>"m.php?m=Deal&a=index&"); 
		}
		
}
